/* 
 * This is the webpage for our wedding.
 * And I take this opportunity to finally play around with jQuery...
 * Also I want to try some of the CCS3 features, but still beeing able to kinda fall back to IE
 *
 * O yeah, and if you are nerd enough to even look at the code of my wedding page,
 * you should seriously think about getting away from your screen and buy some sheep yourself!
 *
 * Designed and coded by Felix Nyffenegger
 *
 * Fazit about jQuery:
 * - Code was implemented very fast (big plus here!)
 * - It's great to manipulate DOM related objects
 * - For big applications it does not help me to design a proper architecture in a mannar YUI would do
 *   (but maybe I am still missing a lot points about jQuery)
 * - A bit disappointed, that I still have to fight a lot with IE. There seams to be a tradeoff. With YUI2 I almost never
 *   have trouble with IE (except for performance reasons). But graphical design freedom is very limmited. With jQuery one
 *   has a lot of freedom, but jQuery does not help to solve all the nasty Browser dependancy issues.
 *
 * Since the wedding is over I disabled the "shop" functionallity but it is still readable below.
 *
 *
 */


// Ok, this a very simple way to encapuslate the code into a local namesapece
$(document).ready(function(){

    ///////////////////////////////////////////////////////////////////////////
    // Init variables, objects and functions defined by me in the app scope
    // (i just abuse the jQuery namespace here, sorry for this...)

    // Remeber the last page for navigation
    $.lastPage = "#pageEmpty";
    // This is the number of green fieds dispalyed
    $.fieldSize = 198;
    // This is the object to collect the items and calculate the bill
    $.bill = {
        total : function () {
            var count = 0;
            $.each(this.items, function(index, value) {
                //count += item.prize;
                count += value.prize;
            })
            return count;
        },
        items : [],
        removeLastItem : function() {
            // do remove
            $.bill.items.splice($.bill.items.length-1, 1);
            updateStatus();
        }
    };

    // And some local methods I need
    var updateStatus = function() {
        $( '#total' ).html($.bill.total());
    }

    // Do the navigation (skip the animation stuff, since IE and opacity suck)
    var showPage = function (page) {
        $( $.lastPage ).css('display','none');
        //$( $.lastPage ).css('opacity', 0 );
        $( page ).css('display','block');
        /*$( page ).animate({
            opacity: 1
        }, 1000 );*/
        $.lastPage = page;
    }

    ////////////////////////////////////////////////////////////
    // Init buttons and dialogs, basic styles and UI events

    // Define the events and animations to display the pages
    $( "#mainTitle").click( function() {
        $( $.lastPage ).css('display','none');
    });
    $( "#kirche").click( function() {
        // showPage("#pageKirche");  
        showPage("#pageBilder");
    });
    $( "#fragen").click( function() {
        showPage("#pageFragen");
    });
    $( "#essen").click( function() {
        //showPage("#pageEssen");
        showPage("#pageRezepte");

    });

    $( "#playlist").click( function() {
        showPage("#pagePlaylist");
    });


    $( "#geschenke").click( function() {
        showPage("#pageGeschenke");
    //$( "#game" ).show();
    //$( "#main" ).hide();
    // Stop showing this info, since purchasing is disabled
    // $( "#dlgInfo").dialog('open');
    // Opacity animation disabled, due to nasty randering in IE (kind of artefacts)
    /*$( "#main" ).animate({
            opacity: 0
        }, 1000, function() {
            $( "#main" ).css('display','none');
            $( "#game" ).css('display','block');
            $( "#game" ).animate({
                opacity: 1
            }, 1000 );
        })*/
    });

    $( "#gallery" ).EmbedPicasaGallery('nyfelix',{
        albumid:    '5658542838452623585',
        matcher:    /./,
        size:      '95',  // thumb size (32,48,64,72,144,160))
        msg_loading_list :  'Loading list from PicasaWeb',
        msg_back :   'Back'
    });

    // Define Buttons and their events
    $( "button" ).button();
    $( "#checkout" ).click(function() {
        if ($.bill.total() > 0) {
            $( "#dlgCheckout").dialog('open');
        } else {
            alert('Du hast noch kein Geschenk auf die Wiese gezogen!');
        }

    });

    
    $( "#backhome" ).click(function() {
        $( "#game" ).hide();
        $( "#main" ).show();
    });

    // Deifine Dialogs and their behavior
    $( "#dlgCheckout").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        buttons: {
            "Ok": function() {
                if ($( "#submitForm" ).valid()) {
                    $( "#submitting" ).show();
                    $( "#dlgCheckout" ).parent().find("button:contains('Ok')").hide();
                    $( "#dlgCheckout" ).parent().find("button:contains('Abbrechen')").hide();
                    var post = {
                        content : {
                            itmes: encodeURI(JSON.stringify($.bill.items)),
                            name : $( "#name").val(),
                            email: $( "#email").val(),
                            total: $.bill.total()
                        }
                    };
                    $.post('services/save.php', post, function(data) {
                        // Change the buttons wich is kind of a hack in jQuery...
                        $( "#submitting" ).html('Vielen Dank, Dein Beitrag wurde übermittelt. Du solltest demnächst eine Email von uns erhalten...');
                        $( "#dlgCheckout" ).parent().find("button:contains('Schliessen')").show();
                    });
                }
            },
            "Abbrechen": function() {
                $(this).dialog("close");
            },
            "Schliessen": function() {
                $(this).dialog("close");
                // Reset all the data:
                $.bill.items = [];
                updateStatus();
                // Go back to the main page
                $( "#game" ).hide();
                $( "#main" ).show();
            }
        },
        closeOnEscape: false,
        open: function(event, ui) {
            $(".ui-dialog-titlebar-close").hide();
            $( "#submitting" ).hide();
            $( "#dlgCheckout" ).parent().find("button:contains('Schliessen')").hide();
            $( "#dlgCheckout" ).parent().find("button:contains('Ok')").show();
            $( "#dlgCheckout" ).parent().find("button:contains('Abbrechen')").show();
        }
    });

    $( "#dlgInfo").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            }
        }
    });

    // Add validation to the dialog formSchliessen
    $( "#submitForm" ).validate({
        rules: {
            name: "required",
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            name: "Bitte gib Deinen Namen an!",
            email: {
                required : "Wir brauchen eine gültige Email von Dir!",
                email: "Wir brauchen eine gültige Email von Dir!"
            }
        }
    });
    
    $( "#dlgVoice").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        close:false,
        buttons: {
            "Ok": function() {
                $.bill.items[$.bill.items.length-1].text = $("#symboltext").val();
                $("#symboltext").val("");
                $(this).dialog("close");
            },
            "Abbrechen": function() {
                $.bill.removeLastItem();
                $( "#" + $.currentField).html("");
                $(this).dialog("close");
            }
        },
        closeOnEscape: false,
        open: function(event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        }
    });



    ////////////////////////////////////////////////////////////////////////
    // Finally define my own UI element, the green field with its behavior

    // Init basic drag behavior for present items
    var moveToOrigin = function(element) {
        $(element)
        .css('left', 0)
        .css('top', 0);
    }
    
    // Define the draggable elements (squares)
    // Disable dragging after after the wedding
    /*

     $( ".symbol" ).draggable({
        stop: function(event, ui) {
            moveToOrigin($(this));
        }
    });
    */


    // Init the drop behavior
    /*var dropoptions = {
        drop: function(event, ui) {
            // Nove the original back
            if ($(ui.draggable).hasClass("symbol")) {
                moveToOrigin(ui.draggable);
                // Append a clone to this square, if nothing is there yet
                if (!$(this).has('.symbol').length) {
                    $(this).append(ui.draggable.clone().css("z-index", 100));
                    //$(this).append($("<div class='close'>x</div>"));
                    // Push item to the bill
                    var amount = 0;
                    switch (ui.draggable.context.id) {
                        case "cat" :
                            amount = 50;
                            break;
                        case "sheep":
                            amount = 50;
                            break;
                        case "duck":
                            amount = 25;
                            break;
                        case "grill":
                            amount = 100;
                            break;
                        case "zelt":
                            amount = 200;
                            break;
                        case "feuer":
                            amount = 30;
                            break;

                    }
                    $.bill.items[$.bill.items.length] = {
                        prize : amount,
                        type  : ui.draggable.context.id,
                        text  : 'Meow',
                        index : this.id
                    }
                    updateStatus(ui.draggable);
                    // Move to near field and open
                    $.currentField = this.id;
                    $( "#dlgVoice" ).dialog('open');
                }
            }
        },
        hoverClass: 'greenfielddrophover'
    }*/

    // Create the Green Field
    $.hzNumFields = $.fieldSize;
    for (var x=0; x<$.hzNumFields; x++) {
        var child = $('<div id="'+ x +'" class="rounded-sm"></div>')
        .addClass('greenfield')
        //.droppable(dropoptions);
        $( "#green" ).append(child);
    }
        
    // Populate the Green with known elements
    $.getJSON('services/load.php', '', function(data, textStatus, xhr) {
        $.hzData = data;
        for(var i=0; i< data.length; i++) {
            if (data[i] != undefined) {
                // Another strage hack we have to do in IE. It seems that the JSON array created by getJSON returns
                // an empty object at the end, but only in IE...
                if (data[i].index != "") {
                    $sym = $( "#nav #" + data[i].type ).clone();
                    $( "#green #" + data[i].index ).append($sym).css("z-index", 100);
                    $sym.dataid = i;
                }
            }
        }
        $(".symbol").click(function () {
            var el = $(this).parent()[0];
            var top = $(el).position().top + $('#green').scrollTop();
            var i = el.id;
            var left = $(el).position().left
            sayMyText(i,top, left);
        })

    })



    // Let the symbols say something
    var sayMyText = function (index, top, left) {
        //if (top > 0 && top < 800) {
        for(var i in $.hzData) {
            if ($.hzData[i].index == index) {
                $("#voice").html("*"+$.hzData[i].text+"*");
                $("#voice").show().css("top", top+5).css("left", left+10);
                window.setTimeout(function() {
                    $("#voice").hide();
                }, 10000);
            }
        }
    //}
    }
    /*
    // Add the random function to invoke the symbols talk
    var hzRandomMessage = function() {
        window.setTimeout(function() {
            // choosesome random symbol
            if ($.hzData != undefined) {
                var len = $.hzData.length;
                var randomnumber = Math.floor(Math.random()*(len))
                //for (var i = randomnumber ; i<$.hzNumFields ; i++) {
                var i = $.hzData[randomnumber].index;
                var el = $( "#green #" + i );
                if ($(el).has('.symbol').length) {
                    var top = $(el).position().top + $('#green').scrollTop();
                    sayMyText(i, top, $(el).position().left);
                    i=$.fieldSize;
                }
            //}
            // Reset the random Message
                
            }
            hzRandomMessage();
        }, 4000);
    };*/
    //hzRandomMessage();

    // Finally try to make IE alos look a bit the same as the rest with help of DD_roundies found here:
    // http://www.dillerdesign.com/experiment/DD_roundies/ (thanks, Drew).
    // Disabled for the small green fields due to
    // 1) quite bad performance in big DOM
    // 2) It takes curious effects on positioning (I guess due to IE restricitve relavtive positioning
    // such as needed in in drag&drop) 

    if (!(typeof(DD_roundies) == 'undefined')) {
        DD_roundies.addRule('.rounded', '12px');
        //DD_roundies.addRule('.rounded-sm', '8px');
        DD_roundies.addRule('button', '4px');
    }
    
});